package com.cloudwise.interceptor;

import com.cloudwise.entity.Tester;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class ApiInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        Tester tester = (Tester) request.getSession().getAttribute("tester");
        if (tester == null){
            response.sendRedirect("/toIndex");
            return false;
        }else {
            if (tester.getTesterName().equals("xxx") && tester.getTesterPhone().equals("xxxxxxxxxxx")){
                if (uri.equals("/toExam")){
                    response.sendRedirect("/toManage");
                    return false;
                }
                return true;
            }else{
                if(uri.equals("/result/selectResult") && tester.getTestTime() != null){
                    return true;
                }
                if ((uri.startsWith("/toExam") || uri.equals("/result/score")) && (tester.getTestTime() == null)){
                    return true;
                }else {
                    response.sendRedirect("/toIndex");
                    return false;
                }
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
